<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：
      </el-breadcrumb-item>
      <el-breadcrumb-item>项目管理</el-breadcrumb-item>
      <el-breadcrumb-item>礼包管理</el-breadcrumb-item>
    </el-breadcrumb>

    <span style="font-size:16px;">{{ giftData.name }}【{{ giftData.id }}】</span><!--礼包名称【礼包ID】-->
    <span style="margin-left:1rem;color:gray;font-size:14px;">礼包状态： <span style="color: green">{{ giftData.status.name }}</span></span>
 
    <!--顶部信息块：-->
    <el-card>
      <el-descriptions>
        <el-descriptions-item label="礼包类别">
          {{ giftData.type.name }}
        </el-descriptions-item>
        <el-descriptions-item label="所属项目">{{
          giftData.project_name
        }}</el-descriptions-item>
        <el-descriptions-item label="对接方式">
          {{giftData.translate_way.name}} 
        </el-descriptions-item>  
        <el-descriptions-item label="结算类型">{{
          giftData.clear_mode.name
        }}</el-descriptions-item>
         <el-descriptions-item label="创建时间">{{
          giftData.create_time
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          giftData.update_time
        }}</el-descriptions-item> 
        <el-descriptions-item label="创建人">{{
          giftData.creaor_name
        }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{
          giftData.remark
        }}</el-descriptions-item>
 
      </el-descriptions>
    </el-card>

    <!--中间按钮块：-->
    <el-row> 
      <el-button
        class="theme-background-color"
        size="medium"
        @click="openEditGiftDialog" 
        >编辑礼包</el-button
      > 
      <el-button
        class="theme-background-color" 
        size="medium"
        @click="openAddGiftRule"
      >
        新增礼包规则
      </el-button>
      <!--礼包状态为开启时，显示-->
      <el-button   
        v-if="giftData.status.id==1"
        size="medium" 
        @click="closeGift"
      >
        关闭礼包
      </el-button> 
    </el-row>

    <!--tab切换块：-->
    <el-tabs v-model="activeName">
      <el-tab-pane label="礼包规则" name="first"></el-tab-pane>
      <el-tab-pane label="操作记录" name="second"></el-tab-pane>
    </el-tabs>
  
    <!-- 定价规则卡片视图区域 -->
    <el-card v-show="activeName === 'first'">
    
      <el-table :data="ruleTableData" border style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
         
              <el-card> 
                <el-table :data="scope.row.price_rule" border style="width: 100%">   
                  <el-table-column label="定价规则ID" width="180"> 
                    <template slot-scope="scope2">{{ scope2.row.id }}</template>
                  </el-table-column>
                  <el-table-column label="结算类型" width="180">
                    <template slot-scope="scope2">{{ scope2.row.clear_mode.name }}</template>
                  </el-table-column>
                  <el-table-column label="计价类型">
                    <template slot-scope="scope2">{{ scope2.row.valuation_type.name }}</template>
                  </el-table-column> 
                  <el-table-column label="统一价">
                    <template slot-scope="scope2">{{ scope2.row.price }}</template> 
                  </el-table-column>
                  <el-table-column label="定价生效日期">
                    <template slot-scope="scope2">{{ scope2.row.start_time }}</template>
                  </el-table-column>
                  <el-table-column label="定价失效日期">
                    <template slot-scope="scope2">{{ scope2.row.end_time }}</template>
                  </el-table-column>
                  <el-table-column label="备注">
                    <template slot-scope="scope2">{{ scope2.row.remark }}</template>
                  </el-table-column>
                  <el-table-column label="操作" ><!---->
                    <template slot-scope="scope2"> 
                      <el-link
                        type="primary" 
                        @click="editPriceRule(scope2.row)"
                      >
                      编辑
                      </el-link> 
                      <!-- &nbsp;
                      <el-link
                        type="primary" 
                        @click="copyPriceRule(scope2.row)"
                      >
                      复制
                      </el-link> -->
                    </template>
                  </el-table-column>
                </el-table> 
              </el-card>
         
          </template>
        </el-table-column>
        
        <el-table-column prop="id" label="礼包规则ID" width="180">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column prop="category" label="券类型" width="180">
          <template slot-scope="scope">{{ scope.row.category.name }}</template>
        </el-table-column>
        <el-table-column prop="service_name" label="服务名称">
          <template slot-scope="scope">{{ scope.row.service_name }}</template>
        </el-table-column>
        <el-table-column prop="ticket_num" label="发券总数">
          <template slot-scope="scope">{{ scope.row.ticket_num }}</template>
        </el-table-column>
       
        <el-table-column prop="period" label="周期">
          <!--判断标识字段待确认：-->
          <template slot-scope="scope">
            <span v-if="scope.row.period_unit.id=='exdate'">{{ scope.row.period }}</span>
            <span v-else>{{ scope.row.period }}{{scope.row.period_unit.name}}</span>
          </template> 
        </el-table-column>
        <el-table-column prop="periodic_release_num" label="每个周期生成券数">
          <template slot-scope="scope">{{ scope.row.periodic_release_num }}</template>
        </el-table-column>
        <el-table-column prop="creator_name" label="创建人">
          <template slot-scope="scope">{{ scope.row.creator_name }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">{{ scope.row.status.name }}</template>
        </el-table-column>
        <el-table-column label="操作"> 
          <template slot-scope="scope">
            <el-link
            type="danger"
            v-show="scope.row.status.id == 2"
            @click="openGiftRule(scope.row)"
            >
            开启
            </el-link>  
            <el-link
              type="danger"
              v-show="scope.row.status.id == 1"
              @click="closeGiftRule(scope.row)"
            >
            关闭
            </el-link> 
            &nbsp;
            <el-link
              type="primary" 
              @click="editGiftRule(scope.row)"
            >
            编辑
            </el-link><!-- v-show="scope.row.status.id == 1 || scope.row.status.id == 2"-->
             <!-- &nbsp;
            <el-link
              type="primary" 
              @click="copyGiftRule(scope.row)"
            >
            复制
            </el-link> -->
             &nbsp;
            <el-link
              type="primary" 
              @click="addPriceRule(scope.row)"
            >
            新增定价
            </el-link>

          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 操作记录卡片视图区域 -->
    <el-card v-show="activeName === 'second'">
      <el-row>
        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in logData"
            :key="index"
            :timestamp="item.create_time + '【' + item.operator_name + '】'"
            >{{ item.operation_desc }}
          </el-timeline-item>
        </el-timeline>
      </el-row>
    </el-card>

  
    <!-- 编辑礼包信息弹窗 -->
    <el-dialog
      title="编辑礼包" 
      :visible.sync="openEditGiftDialogVisible"
      width="50%"
      :before-close="editGiftDialogClose"
      
    >
      <!-- 礼包信息表单 -->
      <GiftBasicInfo 
         :giftInfo="giftInfo" 
          ref="giftInfoFormRef"
          @getGiftInfo="getGiftInfoData"
      ></GiftBasicInfo>  
      <span slot="footer" class="dialog-footer">
        <el-button @click="openEditGiftDialogVisible = false">取 消</el-button> 
        <el-button class="theme-background-color" @click="saveGiftData"> 确 定 </el-button>
      </span>
    </el-dialog>
 
    <!-- 新增礼包规则弹窗 -->
    <el-dialog
      title="新增礼包规则"
      :visible.sync="openAddGiftRuleDialog"
      width="40%" 
      :before-close="AddGiftRuleDialogClose"
    >  
      <GiftRuleBasicInfo 
        :gift_type="gift_type"
        ref="giftRuleBIFormRef"
        @getGiftRule="getGiftRuleData"
      ></GiftRuleBasicInfo>   
      <span slot="footer" class="dialog-footer">
        <el-button @click="openAddGiftRuleDialog = false">取 消</el-button>
        <el-button class="theme-background-color" @click="saveGiftRuleData" :disabled="isSaveGiftRule" >确 定</el-button>
      </span>
    </el-dialog>
   
    <!-- 编辑礼包规则弹窗 --> 
    <GiftRuleEdit  
      :gift_type_id="gift_type_id"
      :editGRId="editGRId"
      ref="giftRuleFormRef"
      :openEditGiftRuleDialog.sync="openEditGiftRuleDialog" 
      @reFill="reGetGiftDetail"
    ></GiftRuleEdit>  

    <!--新增定价规则弹框：--> 
    <el-dialog
      title="新增定价规则" 
      :visible.sync="addPriceRuleDialog"
      width="50%"
      :before-close="addPriceRuleClose"
    > 
      <PriceRuleAdd  
        v-if="hackReset_price"
        :fixdata='fixdata'  
        ref="priceRuleRef"  
        @showPriceRuleRef="getPriceRuleRefData"
      >  
      </PriceRuleAdd> 
      <span slot="footer" class="dialog-footer"> 
        <el-button class="theme-background-color" @click="savePriceRule" :disabled="isAddPriceRule">
          保存
        </el-button> 
      </span>
    </el-dialog>
   
    <!--编辑定价规则弹框：--> 
    <el-dialog
      title="编辑定价规则" 
      :visible.sync="editPriceRuleDialog"
      width="50%"
      :before-close="editPriceRuleClose"
    > 
      <PriceRuleEdit  
        v-if="hackReset"
        :PRData="toEditPRData"
        ref="priceRuleFormRef"  
        @showPriceRuleRef="getPriceRuleRefData" 
      >   
      </PriceRuleEdit> 
      <span slot="footer" class="dialog-footer"> 
        <el-button class="theme-background-color" @click="saveEditPriceRule" :disabled="isEditPriceRule">
          保存
        </el-button> 
      </span>
    </el-dialog>
    
  </div>
</template>

<script> 
 import GiftBasicInfo from './GiftBasicInfo.vue'
 import GiftRuleBasicInfo from './GiftRuleBasicInfo.vue'
 import GiftRuleEdit from './GiftRuleEdit.vue'
 import PriceRuleAdd from './PriceRuleAdd.vue'
 import PriceRuleEdit from './PriceRuleEdit.vue'

export default {
  components: { 
     GiftBasicInfo,
     GiftRuleBasicInfo, 
     GiftRuleEdit,
     PriceRuleAdd,
     PriceRuleEdit
  },
  data() {
    return { 
       
      activeName: 'first',
  
      openEditGiftDialogVisible:false,     //打开编辑礼包的弹框
      openAddGiftRuleDialog:false,  //打开新增礼包规则的弹框
      openEditGiftRuleDialog:false, //打开编辑礼包规则的弹框

      addPriceRuleDialog:false,   //新增定价规则
      editPriceRuleDialog:false,  //编辑定价规则

      giftData:{      //礼包信息
        status:{},
        type:{},
        translate_way:{}, 
        clear_mode:{}
      },
      
      ruleTableData: [],  //礼包规则表格数据
      logData: [],        //操作记录
    
      giftRuleData:{},  //礼包规则
      
      priceRuleData:{},   //新增的定价规则
      toEditPRData:{},        //要编辑的定价规则信息
       
      gift_id:'', 
      gift_type:{},      //礼包类型
      gift_type_id:'',
 
      choose_grid:'',   //新增定价规则时：礼包规则id
      
      service_id:'',
      fixdata:{},
      giftInfo:{}, //传到编辑礼包页格式化后的数据
      editGRId:null,

      isSaveGiftRule:false,   //新增礼包规则
      isAddPriceRule:false,   //新增定价规则 保存按钮
      isEditPriceRule:false,  //编辑定价规则 保存按钮
 
      editGiftData:{},
      hackReset:false,
      hackReset_price:false
      
    }
  },
  created() { 
    this.getGiftDetail()  //获取礼包信息 
    this.gift_id=this.$route.query.id 
  }, 
  methods: { 
    
    reGetGiftDetail(){
      this.getGiftDetail()
    },

    async getGiftDetail() {
      // 请求数据
      const { data: res } = await this.$http.post('/admin/gift/detail', {
        id: this.$route.query.id
      })

      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.giftData = res.data
      this.ruleTableData = res.data.gift_rule
      this.logData = res.data.log
      
      // console.log(res.data)
      this.fixdata.gift_name=res.data.name;    
      this.fixdata.gift_id=res.data.id;  
      this.fixdata.clear_mode=res.data.clear_mode;
      this.gift_type=res.data.type
        
      this.gift_type_id=JSON.parse(JSON.stringify(res.data.type)).id

        
    },
  
    getGiftInfoData(data) {
      this.editGiftData = JSON.parse(JSON.stringify(data)) 
    }, 
    async saveGiftData() {    //编辑礼包信息后的“保存”操作： 
      const flag = await this.$refs.giftInfoFormRef.validateForm()
      if (!flag) return
      // console.log(this.giftData)

      this.$refs.giftInfoFormRef.getFinalData()
      
        var postEditData={}
            postEditData.gift_id=this.giftData.id
 
            postEditData.name=this.editGiftData.name 
            postEditData.translate_way=this.editGiftData.translate_way
            postEditData.project_limit_num=this.editGiftData.project_limit_num
            postEditData.user_limit_num=this.editGiftData.user_limit_num
            postEditData.sms_id=this.editGiftData.sms_id
            postEditData.sms_content=this.editGiftData.sms_content
            postEditData.remark=this.editGiftData.remark
    
      // 向后端发起请求
      const { data: res } = await this.$http.post( '/admin/gift/editGift', postEditData )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('编辑礼包成功')
      this.getGiftDetail()
      this.openEditGiftDialogVisible = false

      this.$refs.giftInfoFormRef.resetAllData()

    },
    
    //礼包规则：开启
    async openGiftRule(row){
      // console.log(row) 
      const confirmResult = await this.$confirm('确定开启该礼包规则【'+row.id+'】吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消操作')
      }
      const { data: res } = await this.$http.post('/admin/gift/activeGiftRule', {
        id: row.id,
        active:'active'
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('成功开启')
      this.getGiftDetail()
    },
    //礼包规则：关闭
    async closeGiftRule(row){
   
      this.$prompt('确定关闭改礼包规则【'+row.id+'】吗？关闭后不可使用', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^(?!.{500}|^\s*$)/g,
        inputErrorMessage: '请输入关闭原因',
        closeOnClickModal: false
      })
        .then(async ({ value }) => {
          // console.log(value)
          const { data: res } = await this.$http.post('/admin/gift/activeGiftRule', {
            id: row.id, 
            reason: value,
            active:'close' 
          })
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('成功关闭')
          this.getGiftDetail() 
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },   

    editGiftRule(row){
  
      this.editGRId=Number.parseInt(row.id) 
      this.openEditGiftRuleDialog = true 
      
    },
  
    //礼包规则：复制
    // copyGiftRule(row){

    // },
    
    //礼包规则：新增定价规则
    addPriceRuleClose(){
      this.$confirm('确认关闭？')
        .then((_) => {
          this.addPriceRuleDialog=false
           // 清空校验
          //待测试： this.$refs.priceRuleRef.resetAllData()
          done()
        })
        .catch((_) => {})
    },
    addPriceRule(row){ 
      this.hackReset_price = false
      this.$nextTick(() => {
        this.hackReset_price = true
      })
    
      this.addPriceRuleDialog=true
    
      this.choose_grid=row.id
      this.fixdata.service_id=row.service_id  
      //还有gift_name和clear_mode在获取礼包信息时绑定
    },
     
    //获取子组件的定价规则数据
    getPriceRuleRefData(data) {
     
      this.priceRuleData = JSON.parse(JSON.stringify(data))  
      // console.log(this.priceRuleData)
   
    },  
    //保存定价规则：隐藏弹框；获取值
    async savePriceRule(){
     
      const flag = this.$refs.priceRuleRef.validateForm()
      if (!flag) return
       
      this.$refs.priceRuleRef.getFinalData()
 
      if (this.priceRuleData.is_diff && this.priceRuleData.diff_rule.length === 0) {
        return this.$message.error('请配置差异价规则')
      }
    
      var addPriceRuleData={}
          addPriceRuleData.gift_id=this.giftData.id
          addPriceRuleData.rule_id=this.choose_grid
        
          addPriceRuleData.service_id=this.priceRuleData.service_id 
          addPriceRuleData.price=this.priceRuleData.price
          addPriceRuleData.start_time=this.priceRuleData.start_time
          addPriceRuleData.end_time=this.priceRuleData.end_time
          addPriceRuleData.remark=this.priceRuleData.remark  
          addPriceRuleData.diff_rule=this.priceRuleData.diff_rule 
 
          if(this.priceRuleData.clear_mode.id!=3){  //结算类型为不结算时：（定价类型）无传参 
            addPriceRuleData.valuation_type=this.priceRuleData.valuation_type //定价类型  .id
          }
          //console.log("要提交的定价规则数据："); console.log(addPriceRuleData);

          const { data: res } = await this.$http.post('/admin/gift/addPriceRule', addPriceRuleData)

          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.isAddPriceRule=true 
          setTimeout(()=>{
              this.isAddPriceRule=false  
          },3000)
          this.addPriceRuleDialog=false; 
          this.$message.success('新增定价规则成功') 
          this.getGiftDetail()
          this.$refs.priceRuleRef.resetAllData()  
 
    }, 
     
    //中间按钮块：start   
    editGiftDialogClose(){    //编辑礼包弹框的关闭事件
      this.$confirm('确认关闭？')
        .then((_) => {
          this.openEditGiftDialogVisible=false  
          this.$refs.giftInfoFormRef.resetAllData()
          done()
        })
        .catch((_) => {})
    }, 
    
    openAddGiftRule(){
      this.openAddGiftRuleDialog=true 
    },  
    AddGiftRuleDialogClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => { 
          this.openAddGiftRuleDialog=false
          this.$refs.giftRuleBIFormRef.resetAllData()    // 清空校验
          done()
        })
        .catch((_) => {})
    }, 
    getGiftRuleData(data){
      this.giftRuleData = JSON.parse(JSON.stringify(data))
    }, 
    async saveGiftRuleData() {  //新增礼包规则：
      const flag = this.$refs.giftRuleBIFormRef.validateForm()
      if (!flag) return
      this.$refs.giftRuleBIFormRef.getFinalData()
      // console.log(this.giftRuleData)
       
      const postData = Object.assign(
        this.giftRuleData,
        { gift_id: this.gift_id } 
      )

      // 向后端发起请求
      const { data: res } = await this.$http.post('/admin/gift/addGiftRule', postData)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.isSaveGiftRule=true 
       setTimeout(()=>{
           this.isSaveGiftRule=false  
      },3000)

      this.$message.success('成功新增礼包规则')
      this.getGiftDetail()
      this.openAddGiftRuleDialog = false 
      this.$refs.giftRuleBIFormRef.resetAllData()
    },

    closeGift() {   //按钮块的关闭礼包事件: 
  
      this.$prompt('是否确认关闭礼包'+this.giftData.name+'【' + this.giftData.id + '】，关闭后不可使用', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^(?!.{500}|^\s*$)/g,
        inputErrorMessage: '请输入关闭原因',
        closeOnClickModal: false
      })
        .then(async ({ value }) => {
          // console.log(value)
          const { data: res } = await this.$http.post('/admin/gift/activeGift', {
            id: this.giftData.id,
            reason: value,
            active:'close'
          })
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          
          this.getListData()
        })
        .catch(() => {
        //  this.$message.info('已取消操作')
        })
 
    },

     //中间按钮块：end
    
    //定价规则：编辑
    editPriceRuleClose(){
       this.$confirm('确认关闭？')
        .then((_) => {
          this.editPriceRuleDialog=false
           // 清空校验
          this.$refs.priceRuleRef.resetAllData()
          done()
        })
        .catch((_) => {})
    },
    async editPriceRule(row){   //编辑定价规则：获取当前的定价规则内容，成功后打开弹框

      // console.log("定价规则编辑的信息：");console.log(row);  
    
      const postData = Object.assign( 
        { id: row.id } 
      ) 
      const { data: res } = await this.$http.post('/admin/gift/getPriceRules',postData) 
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }else{ 
        this.toEditPRData={} 
        this.toEditPRData=res.data  
        this.toEditPRData.clear_mode=res.data.clear_mode.id//.name
        this.toEditPRData.valuation_type=res.data.valuation_type.id
            
        //  console.log(this.toEditPRData)  
        //  this.$refs.priceRuleFormRef.resetAllData()
 
        this.hackReset = false
        this.$nextTick(() => {
          this.hackReset = true
        })
   
        this.editPriceRuleDialog=true   
      }
  
    },
   
    async saveEditPriceRule(){  //提交 编辑的定价规则

      this.editPriceRuleDialog=false;   
      const flag = this.$refs.priceRuleFormRef.validateForm()
      if (!flag) return
      
      /*调用子组件的方法取值、判断值*/
      this.$refs.priceRuleFormRef.getFinalData()
 
      if (this.priceRuleData.is_diff && this.priceRuleData.diff_rule.length === 0) {
        return this.$message.error('请配置差异价规则')
      }
      
      var editPriceRuleData={} 
          editPriceRuleData.start_time=this.priceRuleData.start_time 
          editPriceRuleData.end_time=this.priceRuleData.end_time   
          editPriceRuleData.remark=this.priceRuleData.remark
          editPriceRuleData.price=this.priceRuleData.price 
 
          if(this.priceRuleData.clear_mode!=3){  //结算类型为不结算时：（定价类型）无传参 
            editPriceRuleData.valuation_type=this.priceRuleData.valuation_type //定价类型 
          } 

          // editPriceRuleData.valuation_type=this.priceRuleData.valuation_type.id 
          editPriceRuleData.id=this.priceRuleData.id
           
      // 向后端发起请求
      const { data: res } = await this.$http.post('/admin/gift/editPriceRule', editPriceRuleData)  
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // this.$refs.priceRuleFormRef.resetAllData()
      this.isEditPriceRule=true
      setTimeout(()=>{
          this.isEditPriceRule=false  
      },3000)
      this.$message.success('编辑定价规则成功') 
      this.getGiftDetail()



    },
    getDetailData(){
      this.giftInfo = {
          name: this.giftData.name,
          type: this.giftData.type.id,
          project_id: this.giftData.project_id,
          translate_way: this.giftData.translate_way.id,
          clear_mode: this.giftData.clear_mode.id,
          user_limit_num: this.giftData.user_limit_num,
          project_limit_num: this.giftData.project_limit_num,
          sms_id: this.giftData.sms_id,
          sms_content: this.giftData.sms_content,
          remark: this.giftData.remark
      }
    },
    openEditGiftDialog(){

      this.getDetailData()
      this.openEditGiftDialogVisible = true
    }
    //定价规则：复制
    // copyPriceRule(item){

    // },
 
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin: 10px 0;
}
.el-timeline {
  margin-left: -40px;
  width: 100%;
}

 
</style>
